#!/usr/bin/env python
# Create a new Sage Notebook spkg.

import os
import sys
import stat
import shutil
import tarfile
import subprocess
from tempfile import mkdtemp

from pkg_resources import Requirement
from setuptools.package_index import PackageIndex

# Get the version from setup.py.
version_line = [f for f in open('setup.py').readlines() if 'version' in f][0]
i = version_line.find("'")
j = version_line.rfind("'")
version = version_line[i + 1:j]

# Create the source distribution.
proc = subprocess.Popen([os.path.join(os.path.curdir, 'sdist')], shell=True)
if proc.wait():
    print "Uncommitted changes in repository.  Stopping."
    sys.exit(1)

# Create the spkg.
base = 'sagenb-%s' % version
path = os.path.join('dist', base)
if os.path.exists(path):
    shutil.rmtree(path)
os.makedirs(path)

file = 'sagenb-%s.tar.gz' % version
print "Extracting %s" % file
t = tarfile.open(os.path.join('dist', file))
t.extractall(path)

os.chdir(path)
os.mkdir('src')
shutil.move(base, os.path.join('src', 'sagenb'))

spkg_install = os.path.abspath(os.path.join(os.path.curdir, 'spkg-install'))
spkg_install_fd = open(spkg_install, 'w')
spkg_install_fd.write("cd src\n")

shutil.copy(os.path.join(os.path.pardir, os.path.pardir, 'SPKG.txt'),
            os.path.curdir)



def fetch_packages():
    # This block is here in case we ever need it again.
    print "Fetching the required packages"
    pkg_index = PackageIndex()

    tmp_dir = mkdtemp()


    required_packages = ()

    pkg_locations = []

    for pkg in required_packages:
        print "Fetching %s" % pkg
        dist = pkg_index.fetch_distribution(Requirement.parse(pkg), tmp_dir,
                                            True, True)
        pkg_locations.append(os.path.abspath(dist.location))

    for location in pkg_locations:
        shutil.copy(location, 'src')
        spkg_install_fd.write('easy_install %s\n' % os.path.basename(location))

    return [os.path.basename(location) for location in pkg_locations]

os.chdir(os.path.pardir)

spkg_install_fd.write("""
cd sagenb
python setup.py install

mkdir -p "$SAGE_ROOT/devel"

echo "Copying SageNB package to '$SAGE_ROOT/devel/sagenb-main'."
if [ -d "$SAGE_ROOT/devel/sagenb-main" ]; then
  echo "Copying old SageNB package to '$SAGE_ROOT/devel/sagenb-main-old'."
  rm -rf "$SAGE_ROOT/devel/sagenb-main-old"
  cp -pr "$SAGE_ROOT/devel/sagenb-main" "$SAGE_ROOT/devel/sagenb-main-old"
fi

rm -f "$SAGE_ROOT/devel/sagenb"

cd ..
cp -pr sagenb "$SAGE_ROOT/devel/sagenb-main"

cd "$SAGE_ROOT/devel"
ln -snf sagenb-main sagenb

# We use relative paths for relocatability.
cd "$SAGE_ROOT/devel/sagenb"
python setup.py develop --egg-path ../../../../devel/sagenb

cd "$SAGE_ROOT/local/lib/python/site-packages"
sed 's/^.*sagenb.*$/..\/..\/..\/..\/devel\/sagenb/' easy-install.pth > easy-install.pth.new
mv -f easy-install.pth.new easy-install.pth
""")
spkg_install_fd.close()
os.chmod(spkg_install, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP |
         stat.S_IROTH | stat.S_IXOTH)

subprocess.call(['sage -pkg ' + base], shell=True)
